package com.netdimensions.confluence.plugins;

import com.atlassian.confluence.pages.PageManager;
import com.atlassian.confluence.spaces.SpaceManager;
import com.atlassian.confluence.user.AuthenticatedUserThreadLocal;
import com.atlassian.renderer.RenderContext;
import com.atlassian.renderer.v2.RenderMode;
import com.atlassian.renderer.v2.macro.BaseMacro;
import com.atlassian.renderer.v2.macro.MacroException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public abstract class TrainingHistoryMacro extends EkpMacro {
    protected TrainingHistoryMacro() {
    }

    protected final String html(final Element root) {
        final StringBuilder result = new StringBuilder();
        result.append("<table class='confluenceTable'><tbody>");
        result.append("<tr>");
        result.append("<th class='confluenceTh'>Learning Program/Module</th>");
        result.append("<th class='confluenceTh'>Type</th>");
        result.append("<th class='confluenceTh'>Status</th>");
        result.append("</tr>");

        for (final Node enrollment : XPathUtils.nodes("trainingRecord", root)) {
            result.append("<tr>");
            result.append("<td class='confluenceTd'><a href='");
            result.append(XPathUtils.string("link[@rel=\"launch\"]/@href", enrollment));
            result.append("' target='Course'>");
            result.append(XPathUtils.string("learningModule/title", enrollment));
            result.append("</a></td>");
            result.append("<td class='confluenceTd'>Online</td>");
            result.append("<td class='confluenceTd'>In Process</td>");
            result.append("</tr>");
        }

        result.append("</tbody></table>");
        return result.toString();
    }

    protected final String url(final Map params) {
        return UrlUtils.url(functionName(), Arrays.asList(new Parameter("userId", AuthenticatedUserThreadLocal.getUser().getName())));
    }

    abstract String functionName();
}